package com.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/download.do")
public class DownLoadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getParameter("path");
        System.out.println(path);
        File file = new File("D:\\Download\\" + path);
        if (!file.exists()) {
            resp.getWriter().write("您要下载的内容不存在！");
            return;
        }
        path=new String(path.getBytes("UTF-8"),"ISO-8859-1");
        resp.addHeader("content-disposition", "attachment;filename=" + path);
        FileInputStream fis = new FileInputStream(file);
        ServletOutputStream outputStream = resp.getOutputStream();
        byte[] buffer=new byte[1024];
        int length=0;
        while ((length=fis.read(buffer))!=-1){
            outputStream.write(buffer,0,length);
            outputStream.flush();
        }
        fis.close();
        outputStream.close();
    }
}
